package kinon.canteen.fragment.home;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kinon.canteen.R;
import kinon.canteen.activity.PaymentActivity;
import kinon.canteen.adapter.ShopCartAdapter;
import kinon.canteen.application.Constant;
import kinon.canteen.bean.RxBusCartBean;
import kinon.canteen.bean.ShopCartBean;
import kinon.canteen.bean.UpCartBean;
import kinon.canteen.bean.base.BaseBean;
import kinon.canteen.fragment.BaseFragment;
import kinon.canteen.network.HttpManage;
import kinon.canteen.network.http.CommonSubscriber;
import kinon.canteen.network.http.StrCallback;
import kinon.canteen.util.MyDecimalFormat;
import kinon.canteen.util.RxBus;
import kinon.canteen.util.RxUtil;
import kinon.canteen.util.ShardPManager;
import kinon.canteen.view.MyListView;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by luohao on 2017-07-05.
 */

public class ShoppingCartFragment extends BaseFragment implements View.OnClickListener {

    private View mView;

    private TextView tv_title;
    private TextView tv_topMsg;
    private LinearLayout ll_noGoods;
    private LinearLayout ll_goods;
    private FrameLayout fl_foods;
    private FrameLayout fl_goods;
    private RadioButton rb_foods;
    private RadioButton rb_goods;
    private MyListView list_foods;
    private MyListView list_goods;
    private TextView tv_totalNum;
    private TextView tv_totalPrice;
    private Button btn_payment;


    private int mGoodType=-1;
    private ArrayList<ShopCartBean.Carts> foodList;
    private ArrayList<ShopCartBean.Carts> goodList;
    private ShopCartAdapter fAdapter;
    private ShopCartAdapter gAdapter;
    private int totalNum;
    private double totalPrice;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_cart_layout, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            getCart();
        }
    }

    private void initView() {

        tv_title= (TextView) mView.findViewById(R.id.tv_title);
        tv_topMsg= (TextView) mView.findViewById(R.id.tv_topMsg);
        ll_noGoods= (LinearLayout) mView.findViewById(R.id.ll_noGoods);
        ll_goods= (LinearLayout) mView.findViewById(R.id.ll_goods);
        fl_foods= (FrameLayout) mView.findViewById(R.id.fl_foods);
        fl_goods= (FrameLayout) mView.findViewById(R.id.fl_goods);
        rb_foods= (RadioButton) mView.findViewById(R.id.rb_foods);
        rb_goods= (RadioButton) mView.findViewById(R.id.rb_goods);
        list_foods= (MyListView) mView.findViewById(R.id.list_foods);
        list_goods= (MyListView) mView.findViewById(R.id.list_goods);
        tv_totalNum= (TextView) mView.findViewById(R.id.tv_totalNum);
        tv_totalPrice= (TextView) mView.findViewById(R.id.tv_totalPrice);
        btn_payment= (Button) mView.findViewById(R.id.btn_payment);

        tv_title.setText("购物车");
        tv_topMsg.setText("清空");
        tv_topMsg.setVisibility(View.VISIBLE);
        Drawable drawable = getResources().getDrawable(R.drawable.img_clear_pail);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tv_topMsg.setCompoundDrawables(null,null,drawable , null);


        addListener();
        getCart();
        upDataCart();
    }

    private void addListener(){
        tv_topMsg.setOnClickListener(this);
        rb_foods.setOnClickListener(this);
        rb_goods.setOnClickListener(this);
        btn_payment.setOnClickListener(this);
    }

    private void getCart(){
        foodList=new ArrayList<>();
        goodList=new ArrayList<>();
        fAdapter=new ShopCartAdapter(foodList,getActivity(),0);
        gAdapter=new ShopCartAdapter(goodList,getActivity(),1);
        list_foods.setAdapter(fAdapter);
        list_goods.setAdapter(gAdapter);

        Call<String> call=HttpManage.getInstance()
                .getCart(ShardPManager.getInstance().getToken());
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {
                Gson gson=new Gson();
                ShopCartBean shaoCartBean=gson.fromJson(data,ShopCartBean.class);
                showView(shaoCartBean);
            }

            @Override
            public void onError(int code, String error) {
                mToast(error);
            }
        });
    }

    private void showView(ShopCartBean shaoCartBean){
        for(ShopCartBean.Carts carts:shaoCartBean.getShoppingcarts()){
            if(carts.getType()==0){
                foodList.add(carts);
            }else{
                goodList.add(carts);
            }
        }
        fAdapter.notifyDataSetChanged();
        gAdapter.notifyDataSetChanged();
        showGoods();

    }

    private void showGoods(){
//        shwoOld();
        if(foodList.size()==0 && goodList.size()>0){
            ll_goods.setVisibility(View.VISIBLE);
            ll_noGoods.setVisibility(View.GONE);
            setGoodView();
            setVisible(View.GONE,View.VISIBLE);
        }else if(foodList.size()>0 && goodList.size()>0){
            ll_goods.setVisibility(View.VISIBLE);
            ll_noGoods.setVisibility(View.GONE);
            setFoodView();
            setVisible(View.VISIBLE,View.VISIBLE);
        }else if(foodList.size()==0 && goodList.size()==0){
            ll_goods.setVisibility(View.GONE);
            ll_noGoods.setVisibility(View.VISIBLE);
            setFoodView();
        }else{
            ll_goods.setVisibility(View.VISIBLE);
            ll_noGoods.setVisibility(View.GONE);
            setFoodView();
            setVisible(View.VISIBLE,View.GONE);
        }

    }

    private int  countNum(ArrayList<ShopCartBean.Carts> list){
        int num=0;
        for(ShopCartBean.Carts c:list){
            num+=c.getAmount();
        }
        return num;
    }
    private String  countPrice(ArrayList<ShopCartBean.Carts> list){
        double price=0.0;
        for(ShopCartBean.Carts c:list){
            price+=c.getAmount()*c.getPrice();
        }
        String strPrice=String.valueOf(price);
        return strPrice.length()>8?MyDecimalFormat.dFormat(price):strPrice;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_payment:
                if(goodList.size()==0 && foodList.size()==0){
                    return;
                }
                if(totalNum ==0){
                    return;
                }
                Intent intent=new Intent(getActivity(), PaymentActivity.class);
                intent.putExtra("mGoodType",mGoodType);
                startActivityForResult(intent, Constant.SHOP_CART_FRAGMENT);
//                startActivity(intent);

            break;
            case R.id.rb_foods:
                setFoodView();
            break;
            case R.id.rb_goods:
                setGoodView();
            break;
            case R.id.tv_topMsg:
                clearCart();
                break;
        }
    }

    private void upDataCart() {
        RxBus.getDefault().toFlowable(RxBusCartBean.class)
                .subscribeOn(Schedulers.io())
                .compose(RxUtil.<RxBusCartBean>rxSchedulerHelper())
                .subscribeWith(new CommonSubscriber<RxBusCartBean>() {
                    @Override
                    public void onNext(RxBusCartBean upCartBean) {
                         if(upCartBean.getType()==mGoodType){
                             totalPrice += upCartBean.getTotal();
                             totalNum += upCartBean.getAmount();
                             String strPrice = String.valueOf(totalPrice);
                             tv_totalNum.setText(""+ totalNum);
                             tv_totalPrice.setText("" + (strPrice.length() > 8 ?
                                     MyDecimalFormat.dFormat(totalPrice) : strPrice));
                         }

                    }

                    @Override
                    public void onFail(Throwable t, int code, String msg) {

                    }
                });
    }

    private void setVisible(int visible,int gone){
        fl_foods.setVisibility(visible);
        fl_goods.setVisibility(gone);
    }

    private void setFoodView(){
        rb_foods.setChecked(true);
        rb_goods.setChecked(false);
        totalNum=countNum(foodList);
        totalPrice=Double.valueOf(countPrice(foodList));
        tv_totalNum.setText(""+totalNum);
        tv_totalPrice.setText(""+totalPrice);
        mGoodType=0;
    }
    private void setGoodView(){
        rb_foods.setChecked(false);
        rb_goods.setChecked(true);
        totalNum=countNum(goodList);
        totalPrice=Double.valueOf(countPrice(goodList));
        tv_totalNum.setText(""+totalNum);
        tv_totalPrice.setText(""+totalPrice);
        mGoodType=1;
    }
    private void shwoOld(){
        if(foodList.size()==0 && goodList.size()==0){
            setFoodView();
//            setVisible();
        }else if(foodList.size()==0 && goodList.size()>0){
            setGoodView();
//            setVisible();
        }else if(foodList.size()>0 && goodList.size()==0){
            setFoodView();
//            setVisible();
        }else{
            setFoodView();
//            setVisible();
        }
    }

    private void clearCart(){
        Disposable disposable=HttpManage.getInstance()
                .clearCart(ShardPManager.getInstance().getToken())
                .compose(RxUtil.<BaseBean<String>>rxSchedulerHelper())
                .compose(RxUtil.<String>handleResult())
                .subscribeWith(new CommonSubscriber<String>() {
                    @Override
                    public void onNext(String s) {
                        getCart();
                    }

                    @Override
                    public void onFail(Throwable t, int code, String msg) {

                    }
                });

    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
////        Log.e("lh", "requestCode== "+requestCode );
////        Log.e("lh", "resultCode== "+resultCode );
//    }
}
